#pragma once
#include <carbon/defs.h>
#include <chrono>
#include <memory>
#include <unistd.h>

CARBON_NS_BEGIN

class CARBON_API Thread final {
public:
    struct Impl {
        pthread_t   th;             // 线程句柄
        bool        active {false}; // 是否运行
        RunnableFn  fn;             // 执行函数
    };

public:
    Thread();
    Thread(Thread && other);
    Thread(RunnableFn run);
    Thread(RunnableFn run, const std::string &name);

    ~Thread();

    Thread & operator=(Thread &&other);

    operator bool() const;

    unsigned long id() const;
    
    bool joinable() const;
    void join();

public:
    template<typename Duration>
    static void sleep(Duration timeout) { 
        std::chrono::microseconds us = std::chrono::duration_cast<Duration>(timeout);
        usleep(us.count());
    }

    static void yield() ;

private:
    std::unique_ptr<Impl> m_impl;
}; // Thread

CARBON_NS_END
